const Todo = require('../models/Todo')
const { v4: uuidv4 } = require('uuid')

exports.getTodolist = async (req, res, next) => {
  try {
    const todos = await Todo.find();
    res.status(200).json(todos)
  } catch (err) {
    next(err)
  }
}

exports.getTodoById = async (req, res, next) => {
  try {
    const todo = await Todo.findById(req.params._id);
    res.status(200).json(todo)
  } catch (err) {
    next(err)
  }
}

exports.saveTodo = async (req, res, next) => {
  try {
    const todo = new Todo({
      _id: uuidv4(),
      title: req.body.title
    })
    await todo.save()
    res.status(200).json(todo)
  } catch (err) {
    next(err)
  }
}

exports.updateTodo = async (req, res, next) => {
  const todo = await Todo.findByIdAndUpdate(
    req.body._id,
    { title: req.body.title },
    { new: true }
  );
  res.status(200).json(todo)
}

exports.deleteTodoById = async (req, res, next) => {
  try {
    await Todo.findByIdAndDelete(req.params._id);
    res.status(200).send("删除成功")
  } catch (err) {
    next(err)
  }
}